import 'dart:convert';
import 'dart:io';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:get/get.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:package_info/package_info.dart';

///初始化
void initXUpdate({bool isShowToast = false}) async {
  if (Platform.isAndroid) {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String packageName = packageInfo.packageName;
    int buildNumber = int.parse(packageInfo.buildNumber);
    FlutterXUpdate.init(

            ///是否输出日志
            debug: true,

            ///是否使用post请求
            isPost: false,

            ///post请求是否是上传json
            isPostJson: false,

            ///请求响应超时时间
            timeout: 25000,

            ///是否开启自动模式
            isWifiOnly: false,

            ///是否开启自动模式
            isAutoMode: false,

            ///需要设置的公共参数
            supportSilentInstall: false,

            ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
            enableRetry: false)
        .then((value) {})
        .catchError((error) {
      logger.e(error);
    });
    FlutterXUpdate.setCustomParseHandler(onUpdateParse: (response) async {
      Map<String, dynamic> map = json.decode(response!);
      String updateContent = map['explainInfo'] != null ? map['explainInfo'] as String : "";
      List<String> updateContentList = updateContent.split("|");
      String updateContentWithN = "";
      for (int i = 0; i < updateContentList.length; i++) {
        if (i == updateContentList.length - 1) {
          updateContentWithN += updateContentList[i];
        } else {
          updateContentWithN += "${updateContentList[i]}\n";
        }
      }
      var updateEntity = UpdateEntity(
        hasUpdate: int.parse(map["versionCode"] as String) > buildNumber,
        isForce: (map["forceUpdate"] as int) == 1,
        versionCode: int.parse(map["versionCode"] as String),
        versionName: map['version'],
        updateContent: updateContentWithN,
        downloadUrl: map["downloadAddress"],
        isIgnorable: (map["forceUpdate"] as int) == 1,
      );
      return updateEntity;
    });
    FlutterXUpdate.setErrorHandler(onUpdateError: (Map<String, dynamic>? message) async {
      if (isShowToast) {
        if (message != null && message['code'] == 2004) {
          ToastUtil.normal(MultiLanguage.theCurrentVersionIsUpToDate.tr);
        }
      }
      logger.e(message);
      // setState(() {
      //   _message = "$message";
      // });
    });
    FlutterXUpdate.checkUpdate(
        url: Apis.APP_UPDATE,
        isCustomParse: true,
        params: {"packageName": packageName, "pkType": "1"});
  } else {
    logger.i("ios暂不支持XUpdate更新");
  }
}
